package com.zhangdi.dwperms.service.impl;

import com.zhangdi.dwperms.bo.ShiroAccount;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;

import java.util.Iterator;

/**
 * Created by zhangdi on 2020/01/13 16:03:29.
 */
public class BaseSubject {
    protected static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    protected ShiroAccount getCurrentUser() {
        return (ShiroAccount) getSubject().getPrincipal();
    }

    protected Session getSession() {
        return getSubject().getSession();
    }

    protected Session getSession(Boolean flag) {
        return getSubject().getSession(flag);
    }

    protected void doLogin(AuthenticationToken token) {
        getSubject().login(token);
    }

    public Long getUserId() {
        return getCurrentUser().getUserId();
    }

    /**
     * 修改权限后要更新用户的信息
     */
    protected void clearAuthz() {
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        Iterator<Realm> iterator = securityManager.getRealms().iterator();
        while (iterator.hasNext()) {
            AuthorizingRealm realm = (AuthorizingRealm) iterator.next();
            realm.getAuthorizationCache().remove(getSubject().getPrincipals());
        }
    }
}
